﻿using System.Linq;
using System.Windows;
using BioHlpLib;

namespace SecurePO
{
    using System;
    using System.Security.Principal;
    using System.Threading;
    using System.Windows.Threading;

    public partial class Window1
    {
        private const decimal ApprovalThreshold = 350;

        public Window1()
        {
            this.InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            FeedbackLink.Click += FeedbackLink_Click;
            
            // Get identity and update UI
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            string userName = ActiveDirectoryHelper.GetUserName(identity.Name);
            userName = string.IsNullOrEmpty(userName) ? "Guest" : userName;
            UserName.Text = string.Format("Welcome, {0}!", userName);
            this._AddPurchaseOrdersToUI();
        }

        private void FeedbackLink_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("mailto:feedback@jwsecure.com");
        }

        private void _AddPurchaseOrdersToUI()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            PurchaseOrder[] purchaseOrders = new PurchaseOrder[] { };
            using (SPOEntities entities = new SPOEntities())
            {
                try
                {
                    purchaseOrders = entities.PurchaseOrder.ToArray();
                }
                catch (System.Data.EntityException ex)
                {
                    MessageBox.Show(this, ex.InnerException.Message, "Error");
                    this.Close();
                }
            }

            foreach (PurchaseOrder purchaseOrder in purchaseOrders)
            {
                bool bioIdentityRequired = purchaseOrder.Amount > ApprovalThreshold ? true : false;
                string poUserName = ActiveDirectoryHelper.GetUserNameBySid(purchaseOrder.AddedBy);
                PurchaseOrderItem po = new PurchaseOrderItem { Id = purchaseOrder.Id, Title = purchaseOrder.Title, Description = purchaseOrder.Description, Amount = purchaseOrder.Amount, Added = purchaseOrder.Added, UserName = poUserName, BioIdentityRequired = bioIdentityRequired, CanApprove = identity.User.Value == purchaseOrder.Approver && purchaseOrder.Approved.ToString() == DateTime.MaxValue.ToString(), Approved = purchaseOrder.Approved, Approver = purchaseOrder.Approver };
                po.ApprovalRequested += PurchaseOrderApprovalRequested;
                po.BioApprovalRequested += PurchaseOrderBioApprovalRequested;
                POPanel.Children.Add(po);
            }
        }

        private void _GetFingerprintScan(object info)
        {
            object[] stateInfo = ((object[])info);
            bool isLoggedOnUser = false;
            UInt32 rejectDetail = 0;
            Int32 result = 0;
            if (0 != (result = BioHlpNativeInterface.BHIdentifyAsLoggedOnUser(ref isLoggedOnUser, ref rejectDetail)))
            {
            }
            else if (true == isLoggedOnUser)
            {
                isLoggedOnUser = true;
            }
            else
            {
            }
            if (isLoggedOnUser)
            {
                bool approved;
                using (SPOEntities entities = new SPOEntities())
                {
                    PurchaseOrder statePO = ((PurchaseOrder)stateInfo[0]);
                    PurchaseOrder po = entities.PurchaseOrder.Where(p => p.Id == statePO.Id).FirstOrDefault();
                    po.Approved = DateTime.Now;
                    approved = entities.SaveChanges() > 0;
                }
                if (approved)
                {
                    this.Dispatcher.Invoke(DispatcherPriority.Normal, new System.Windows.Forms.MethodInvoker(delegate()
                    {
                        BioScanDialog.Close();
                        POPanel.Children.Clear();
                        this._AddPurchaseOrdersToUI();
                    }));
                }
            }
        }

        private void PurchaseOrderBioApprovalRequested(object sender, PurchaseOrderItemEventArgs e)
        {
            OperatingSystem system = Environment.OSVersion;
            Version version = system.Version;
            if (version.Major > 5)
            {
                BioScanDialog.Show(this.LayoutRoot);
                object[] stateInfo = new object[] { e.PO };
                System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(_GetFingerprintScan), stateInfo);
            }
            else
            {
                MessageBox.Show("Biometric approval of purchase orders is only available on Windows version 7 and above.", "Biometric Approval Not Available");
            }
        }

        private void PurchaseOrderApprovalRequested(object sender, PurchaseOrderItemEventArgs e)
        {
            if (MessageBoxResult.Yes == MessageBox.Show(string.Format("Do you wish to approve \"{0}\" in the amount of {1:C}?", e.PO.Title, e.PO.Amount), "Approve Purchase Order", MessageBoxButton.YesNo))
            {
                bool approved;
                using (SPOEntities entities = new SPOEntities())
                {
                    PurchaseOrder po = entities.PurchaseOrder.Where(p => p.Id == e.PO.Id).FirstOrDefault();
                    po.Approved = DateTime.Now;
                    approved = entities.SaveChanges() > 0;
                }
                if (approved)
                {
                    POPanel.Children.Clear();
                    this._AddPurchaseOrdersToUI();
                }
            }
        }

        private void Button_New_Order_Click(object sender, RoutedEventArgs e)
        {
            NewPurchaseOrderItem npo = new NewPurchaseOrderItem { IsNew = true };
            npo.Cancelled += NewPurchaseOrderCancelled;
            npo.SaveRequested += NewPurchaseOrderSaveRequested;
            POPanel.Children.Insert(0, npo);
        }

        private void NewPurchaseOrderSaveRequested(object sender, NewPurchaseOrderSaveEventArgs e)
        {
            PurchaseOrder po = e.PO;
            bool saved;
            using (SPOEntities entities = new SPOEntities())
            {
                entities.AddToPurchaseOrder(po);
                saved = entities.SaveChanges() > 0;
            }
            if (saved)
            {
                POPanel.Children.Clear();
                this._AddPurchaseOrdersToUI();
            }
        }

        private void NewPurchaseOrderCancelled(object sender, EventArgs e)
        {
            POPanel.Children.Remove(((UIElement)sender));
        }
    }
}